<template>
  <div class="order">
    <van-sticky>
      <van-nav-bar :title="$route.meta.title" left-arrow @click-left="onClickLeft" style="width:100%;" />
    </van-sticky>
    <van-form @submit="onSubmit">
      <div class="order-body">
        <div class="order-body-takeover">
          <van-cell :title="address==''?'暂无收货地址':address.address" icon="" :border="false" center>
            <template #right-icon>
              <van-icon :name="require('@/assets/locations.png')" />
            </template>
          </van-cell>
          <div class="recipient">
            <van-cell :title="address==''?'暂无收货人':address.name" :border="false" />
            <van-cell :title="address==''?'暂无收货人联系方式':address.tel" :value="address==''?'添加地址':'选择地址'" value-class="fs" is-link :border="false" @click="gopath" />
          </div>
        </div>
        <div class="order-value">
          <div v-for="(item, index) in list" :key="index">
            <van-card :num="item.amount" :price="item.issprice==1?item.sprice:item.productprice" :title="item.productname" :thumb="img + item.imgarr[0]" />
          </div>
        </div>
        <div class="order-payway">
          <van-cell is-link title="备注" :value="remark" @click="showPicker1 = true" :border="false" />
          <van-popup v-model="showPicker1" position="bottom" round closeable :style="{ height: '40%' }">
            <van-field v-model="remark" class="order-remark" autosize label="备注" type="textarea" maxlength="100" placeholder="口味、偏好等要求" show-word-limit @confirm="onConfirm1" @cancel="showPicker1 = false" />
          </van-popup>
        </div>
      </div>
      <div style="height:1.34rem"></div>
      <div class="order-foot">
        <div class="foot-total">
          <div class="foot-price">
            <span>￥{{ money }}</span>
          </div>
          <div class="submit-order">
            <van-button type="warning" native-type="submit">提交订单</van-button>
          </div>
        </div>
      </div>
    </van-form>
  </div>
</template>
<script>
import Vue from "vue";
import { Dialog, Toast } from "vant";
Vue.use(Dialog, Toast);
export default {
  name: "PlaceOrder",
  data () {
    return {
      shopid: 0,
      money: 0,
      list: [],
      orderlist: 0,
      showPicker1: false,
      showPicker2: false,
      remark: "",
      orderid: "",
      address: "",
      goaddress: "",
      type: '',
      // pay_params: {}, // 支付参数
    };
  },
  methods: {
    getMyAddress () {
      this.$axios("/buy/getmyaddresslist")
        .then((res) => {
          if (res.data.data.length != 0) {
            var addlist = res.data.data.map((v) => {
              return {
                ...v,
                name: v.user_name,
                tel: v.phone,
                address: v.province + v.city + v.district + v.address,
                addressDetail: v.province + v.city + v.district,
                county: v.district,
                isDefault: v.defaultadd == 1,
                areaCode: JSON.stringify(v.areaCode),
              };
            });
            this.address = addlist[0];
          } else {
            Toast("请填写收货信息");
          }
        });
    },
    gopath () {
      this.$router.push({ path: "/addresss", query: { type: 1 } });
    },
    info (id) {
      this.$axios("/buy/settlement", {
        id: id,
        handle: "", //不填返回订单数据，填即提交以下数据
      }).then((res) => {
        this.list = res.data.data.map(item => {
          return {
            ...item,
            imgarr: item.menuimage.split(',')
          }
        })
      });
    },
    onClickLeft () {
      this.$router.go(-1);
    },
    onConfirm1 (value) {
      this.remark = value;
      this.showPicker1 = false;
    },
    // 结算订单
    onSubmit () {
      this.$axios("/buy/settlement", {
        id: this.orderid, //订单ID
        handle: "ajax", //不填返回订单数据，填即提交以下数据
        address: this.address.id, //收货地址ID
        requiredtime: "", //要求送达时间
        remark: this.remark, //备注
        type: 1, //1-注册时下单；2-普通下单
      }).then((res) => {
        if (res.data.code == 1) {
          this.StartWeiXinPay(res.data.data)
        } else {
          Toast.fail(res.data.msg)
        }
      });
    },
    // 调取微信支付
    StartWeiXinPay (pay_params) {
      if (typeof window.WeixinJSBridge === 'undefined') {
        if (document.addEventListener) {
          alert(1);
          document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady(pay_params), false)
        } else if (document.attachEvent) {
          alert(2);
          document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady(pay_params))
          document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady(pay_params))
        }
      } else {
        this.onBridgeReady(pay_params)
      }
    },
    onBridgeReady (pay_params) {
      var that = this
      window.WeixinJSBridge.invoke('getBrandWCPayRequest', {
        'appId': pay_params.appId, // 公众号名称，由商户传入
        'timeStamp': pay_params.timeStamp, // 时间戳，自1970年以来的秒数
        'nonceStr': pay_params.nonceStr, // 随机串
        'package': pay_params.package, //统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
        'signType': pay_params.signType, // 微信签名方式：
        'paySign': pay_params.paySign // 微信签名
      },
        function (res) {
          if (res.err_msg == 'get_brand_wcpay_request:ok') {
            // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
            Toast.success('下单成功，请等待审核通过后再登录账号')
            setTimeout(() => {
              localStorage.clear()
              that.$router.push({ path: '/login' })
            }, 1000);
          } else {
            Toast.fail('支付失败')
          }
        }
      )
    },
  },
  created () {
    this.orderid = this.$route.query.id;
    this.type = localStorage.getItem("type");
    this.money = this.$route.query.money;
    this.info(this.orderid);
    if (localStorage.getItem("address") == null) {
      this.getMyAddress();
    } else {
      this.address = JSON.parse(localStorage.getItem("address"));
    }
  },
};
</script>

<style lang="less" scoped>
.order {
  display: flex;
  flex-direction: column;
  .order-value {
    /deep/ .van-card__content {
      padding-left: 10px;
      justify-content: space-between;
      min-height: 0;
    }
    /deep/.van-card__thumb {
      width: 1.5rem;
      height: 1.5rem;
    }
    /deep/ .van-card {
      background-color: #fff;
    }
    /deep/ .van-card__title {
      padding-top: 15px;
      font-size: 30px;
      font-weight: bold;
    }
    /deep/ .van-card__price {
      color: red;
      font-weight: bold;
    }
  }
  .order-top,
  .order-body,
  .foot-total,
  .foot-price,
  .submit-order {
    display: flex;
  }
  .order-body {
    width: 90%;
    margin: 20px auto;
    flex-direction: column;
    &-takeover {
      width: 100%;
      box-sizing: border-box;
      margin: 15px auto 15px;
      z-index: 1;
      background-color: #fff;
      border-radius: 15px;
      box-shadow: 0 6px 10px #ddd;
      /deep/ .van-cell {
        border-radius: 15px;
      }
      .recipient {
        padding: 15px 0;
        .fs {
          font-size: 20px;
        }
        /deep/ .van-cell {
          padding: 0 30px;
        }
      }
    }
  }
  .order-value,
  .order-payway {
    width: 100%;
    background-color: #fff;
    border-radius: 15px;
    box-shadow: 0 6px 10px #ddd;
    box-sizing: border-box;
    padding: 10px;
    margin: 15px auto 15px;
    z-index: 1;
  }
  .order-remark {
    margin-top: 50px;
  }
  .order-foot {
    position: fixed;
    background-color: #1bb89c;
    width: 100%;
    height: 1.34rem;
    bottom: 0;
    text-align: right;
    z-index: 999;
  }
  .foot-total {
    width: 100%;
    height: 1.34rem;
  }
  .foot-price,
  .submit-order {
    width: 50%;
  }
  .foot-price {
    font-size: 40px;
    font-weight: bold;
    padding: 10px 25px;
    color: white;
    align-self: center;
  }
  .submit-order {
    justify-content: flex-end;
    /deep/ button {
      height: 1.34rem;
      font-weight: bold;
      border-radius: 0;
    }
  }
}
</style>
